import { Team, TeamMember } from '../../../types/rbac';
import { PageRequest, PageResponse, ApiResponse } from '../../../types';
import api from '../../api';
import { apiModeUtils } from '../../apiConfig';

// 团队查询参数（匹配后端API）
interface TeamQueryParams {
  page?: number;
  size?: number;
  current?: number;
  search?: string;
  keyword?: string;
  name?: string;
  code?: string;
  status?: number; // 后端使用数字：1-正常，0-禁用
  departmentId?: string;
}

// 创建团队API包装器
const api_team = apiModeUtils.createApi('teamApi', api, false);

// 团队API
export const teamApi = {
  // 获取团队列表（分页）
  getTeams: async (params?: PageRequest & { keyword?: string; departmentId?: string | null }): Promise<PageResponse<Team>> => {
    const query = {
      current: params?.page || 1,
      size: params?.size || 10,
      name: params?.keyword,
      code: params?.keyword,
      search: params?.keyword,
      departmentId: params?.departmentId,
      ...params
    };
    
    return api_team.post('getTeams', '/system/api/v3/sys/teams/page', query);
  },

  // 获取团队详情
  getTeam: async (id: string): Promise<Team> => {
    return api_team.get('getTeam', `/system/api/v3/sys/teams/get/${id}`);
  },

  // 创建团队
  createTeam: async (data: Omit<Team, 'id' | 'createTime' | 'updateTime'>): Promise<Team> => {
    return api_team.post('createTeam', '/system/api/v3/sys/teams/add', data);
  },

  // 更新团队
  updateTeam: async (id: string, data: Partial<Team>): Promise<Team> => {
    return api_team.put('updateTeam', '/system/api/v3/sys/teams/update', data);
  },

  // 删除团队
  deleteTeam: async (id: string): Promise<void> => {
    return api_team.delete('deleteTeam', `/system/api/v3/sys/teams/delete/${id}`);
  },

  // 批量删除团队
  deleteTeams: async (ids: string[]): Promise<void> => {
    return api_team.delete('deleteTeams', '/system/api/v3/sys/teams/batch', { data: { ids } });
  },

  // 获取团队成员（分页）
  getTeamMembers: async (teamId: string, params?: PageRequest): Promise<PageResponse<TeamMember>> => {
    const query = {
      teamId: teamId,
      current: params?.page || 1,
      size: params?.size || 10,
      ...params
    };
    
    return api_team.post('getTeamMembers', '/system/api/v3/sys/teams/members/page', query);
  },

  // 添加团队成员
  addTeamMembers: async (teamId: string, userIds: string[]): Promise<void> => {
    return api_team.post('addTeamMembers', `/system/api/v3/sys/teams/${teamId}/members`, { userIds });
  },

  // 移除团队成员
  removeTeamMembers: async (teamId: string, userIds: string[]): Promise<void> => {
    return api_team.delete('removeTeamMembers', `/system/api/v3/sys/teams/${teamId}/members`, { data: { userIds } });
  },

  // 获取用户可加入的团队
  getAvailableTeams: async (userId: string): Promise<Team[]> => {
    return api_team.get('getAvailableTeams', `/system/api/v3/sys/users/${userId}/available-teams`);
  },

  // 获取用户所属团队
  getUserTeams: async (userId: string): Promise<Team[]> => {
    return api_team.get('getUserTeams', `/system/api/v3/sys/users/${userId}/teams`);
  },
};

// Mock API (开发时使用)
export const mockTeamApi = {
  getTeams: async (params?: PageRequest & { keyword?: string; departmentId?: string | null }): Promise<PageResponse<Team>> => {
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const mockTeams: Team[] = [
      {
        id: 'team-001',
        code: 'dev_team',
        name: '开发团队',
        description: '核心开发团队',
        departmentId: 'dept-001',
        level: 1,
        memberCount: 12,
        status: 'active',
        createTime: '2024-01-01',
        updateTime: '2024-01-01',
        createdBy: 'admin',
      },
      {
        id: 'team-002',
        code: 'qa_team',
        name: '测试团队',
        description: '质量保证团队',
        departmentId: 'dept-001',
        level: 1,
        memberCount: 5,
        status: 'active',
        createTime: '2024-01-02',
        updateTime: '2024-01-02',
        createdBy: 'admin',
      },
      {
        id: 'team-003',
        code: 'sales_team',
        name: '销售团队',
        description: '销售业务团队',
        departmentId: 'dept-004',
        level: 1,
        memberCount: 8,
        status: 'active',
        createTime: '2024-01-03',
        updateTime: '2024-01-03',
        createdBy: 'admin',
      }
    ];

    let filteredTeams = mockTeams;
    if (params?.keyword) {
      filteredTeams = mockTeams.filter(team =>
        team.name.includes(params.keyword!) ||
        team.code.includes(params.keyword!) ||
        team.description?.includes(params.keyword!)
      );
    }

    const pageSize = params?.size || 10;
    const pageNumber = params?.page || 1;
    const start = (pageNumber - 1) * pageSize;
    const end = start + pageSize;
    const paginatedTeams = filteredTeams.slice(start, end);

    return {
      records: paginatedTeams,  // 使用records字段匹配后端响应格式
      totalElements: filteredTeams.length,
      totalPages: Math.ceil(filteredTeams.length / pageSize),
      size: pageSize,
      number: pageNumber - 1,
      first: pageNumber === 1,
      last: pageNumber >= Math.ceil(filteredTeams.length / pageSize)
    };
  },

  getTeam: async (id: string): Promise<Team> => {
    await new Promise(resolve => setTimeout(resolve, 300));
    
    const mockTeam: Team = {
      id,
      code: 'dev_team',
      name: '开发团队',
      description: '核心开发团队',
      departmentId: 'dept-001',
      level: 1,
      memberCount: 12,
      status: 'active',
      createTime: '2024-01-01',
      updateTime: '2024-01-01',
      createdBy: 'admin',
    };

    return mockTeam;
  },

  createTeam: async (data: any): Promise<Team> => {
    await new Promise(resolve => setTimeout(resolve, 800));
    
    const newTeam: Team = {
      id: `team-${Date.now()}`,
      ...data,
      memberCount: 0,
      level: 1,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      createdBy: 'current-user',
    };

    return newTeam;
  },

  updateTeam: async (id: string, data: any): Promise<Team> => {
    await new Promise(resolve => setTimeout(resolve, 600));
    
    const updatedTeam: Team = {
      id,
      code: 'updated_team',
      name: '更新的团队',
      description: '更新的描述',
      departmentId: 'dept-001',
      level: 1,
      memberCount: 5,
      status: 'active',
      createTime: '2024-01-01',
      updateTime: new Date().toISOString(),
      createdBy: 'admin',
      ...data,
    };

    return updatedTeam;
  },

  deleteTeam: async (id: string): Promise<void> => {
    await new Promise(resolve => setTimeout(resolve, 400));
  },

  deleteTeams: async (ids: string[]): Promise<void> => {
    await new Promise(resolve => setTimeout(resolve, 600));
  }
};